# -*- coding: utf-8 -*-
"""
非最大/极大值抑制函数：
防止最后图像中的目标区域被多个框框住，
即使用该函数后，可以只用一个框把目标框住。
"""

# import the necessary packages
import numpy as np

# Malisiewicz et al.
# Python port by Adrian Rosebrock
def non_max_suppression_fast(boxes, overlapThresh):
    # if there are no boxes, return an empty list
    if len(boxes) == 0:
        return []

    # if the bounding boxes integers, convert them to floats --
    # this is important since we'll be doing a bunch of divisions
    if boxes.dtype.kind == "i":
        boxes = boxes.astype("float")

    # initialize the list of picked indexes 
    pick = []

    # grab the coordinates of the bounding boxes
    """x,y,w,h"""
    x1 = boxes[:,0]        # 取数组的第一列数据
    y1 = boxes[:,1]        # 取数组的第二列数据
    x2 = boxes[:,2]        # 取数组的第三列数据
    y2 = boxes[:,3]        # 取数组的第四列数据
    scores = boxes[:,4]    # 取数组的第五列数据
    # compute the area of the bounding boxes and sort the bounding
    # boxes by the score/probability of the bounding box
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    idxs = np.argsort(scores)[::-1]      # 先将boxes第五列倒序，再返回他们的大小排序的序号，返回的序号越大，表示相应的分数越大

    # keep looping while some indexes still remain in the indexes
    # list
    while len(idxs) > 0:
        # grab the last index in the indexes list and add the
        # index value to the list of picked indexes
        """取最后一个值并不意味取最大的那个值，因为np.argsort（）并没有对数组里的值进行大小排序"""
        #后面程序会把idxs的值一个一个删掉，最后取出合适的值
        last = len(idxs) - 1
        i = idxs[last]
        pick.append(i)

        # find the largest (x, y) coordinates for the start of
        # the bounding box and the smallest (x, y) coordinates
        # for the end of the bounding box
        """
        把每一列的最大值求出来，
        x1[i]表示上面求出来的最后一个标签所对应的值；
        x1[idxs[:last]]表示除了x1[i]外的所有值。
        """
        xx1 = np.maximum(x1[i], x1[idxs[:last]])
        yy1 = np.maximum(y1[i], y1[idxs[:last]])
        xx2 = np.minimum(x2[i], x2[idxs[:last]])
        yy2 = np.minimum(y2[i], y2[idxs[:last]])

        # compute the width and height of the bounding box
        w = np.maximum(0, xx2 - xx1 + 1)
        h = np.maximum(0, yy2 - yy1 + 1)

        # compute the ratio of overlap
        # 计算重叠率
        overlap = (w * h) / area[idxs[:last]]

	
        # delete all indexes from the index list that have
        '''numpy.delete(arr,obj,axis=None)
        arr:输入向量
        obj:表明哪一个子向量应该被移除。可以为整数或一个int型的向量
        axis:表明删除哪个轴的子向量，若默认，则返回一个被拉平的向量.
        '''
        '''
        numpy.concatenate((a1, a2, ...), axis=0)
        将数组拼接起来
        '''
        '''
        np.where(overlap > overlapThresh)[0]
        如果overlap > overlapThresh为真，就输出[0]，
        为假就输出[]
        '''
        #在这里，如果大于阈值，就删除idxs里第一个跟最后一个值，不大于阈值就只删除最后一个
        idxs = np.delete(idxs, np.concatenate(([last],
                                               np.where(overlap > overlapThresh)[0])))

    # return only the bounding boxes that were picked using the
    # integer data type
    return boxes[pick].astype("int")
